package com.zyf.baselibrary.base

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.example.baselibrary.utils.ViewBindingUtil
import com.example.baselibrary.utlis.GlobalTimer
import com.example.baselibrary.utlis.TimerListener

/**
 * Base Activity with ViewBinding and ViewModel support
 * @param VB Type of ViewBinding
 * @param VM Type of ViewModel
 */
abstract class BaseViewBindingActivity<VB : ViewBinding, VM : BaseViewModel> : BaseActivity() {

    protected val binding: VB by lazy { ViewBindingUtil.inflateWithGeneric(this, layoutInflater) }
    protected val viewModel: VM by lazy { provideViewModel() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initObservers()
    }

    override fun onResume() {
        super.onResume()
        GlobalTimer.registerListener(timerListener)
    }

    override fun onPause() {
        super.onPause()
        // 注销监听器（避免内存泄漏）
        GlobalTimer.unregisterListener(timerListener)
    }

    override fun onDestroy() {
        // Optional: Clear binding reference if needed
        // (ViewBindingUtil should handle this internally)
        super.onDestroy()
    }

    /**
     * Provide ViewModel class for initialization
     */
    protected abstract fun provideViewModel(): VM

    /**
     * Initialize LiveData observers
     */
    protected open fun initObservers() {
        // Default empty implementation
    }

    val timerListener = object : TimerListener {
        override fun onSecondElapsed(millis: Long) {
//            Log.d("Timer", "已运行: ${millis / 1000} 秒")
        }

        override fun onMinuteElapsed(minutes: Long) {
            Log.d("Timer", "已运行: $minutes 分钟")
        }
    }
}